// oss.service.ts
import { Injectable, BadRequestException } from '@nestjs/common';
import * as OSS from 'ali-oss';
import { v4 as uuidv4 } from 'uuid';
import { HttpService } from '@nestjs/axios';

const storagePath = `images/motions/self/`;  // 存储地址
@Injectable()
export class OssService {
  private client: OSS;
  constructor(private readonly httpService: HttpService) {
    this.client = new OSS({
      region: process.env.OSS_REGION,
      accessKeyId: process.env.OSS_ACCESS_KEY,
      accessKeySecret: process.env.OSS_SECRET,
      bucket: process.env.OSS_BUCKET,
    });
  }

  async downloadAndSaveImage(url: string): Promise<string> {
    const ext = url.split('.').pop();
    if (!ext) {
      throw new BadRequestException('URL格式不正确');
    }

    try {
      const response = await this.httpService.axiosRef.get(url, {
        responseType: 'arraybuffer',
      });

      // const ext = url.split('.').pop().toLowerCase();
      if (!['jpg', 'jpeg', 'png'].includes(ext)) {
        throw new Error('仅支持JPG/PNG格式');
      }
      const filename = `${uuidv4()}.${ext}`;

      const result = await this.client.put(
        `${storagePath}${filename}`,
        Buffer.from(response.data),
        { headers: { 'Content-Type': this.getMimeType(ext) } },
      );

      return result.url;
    } catch (error) {
      throw new Error(`OSS上传失败: ${error.message}`);
    }
  }

  // MIME类型映射方法
  private getMimeType(ext: string): string {
    const map = {
      jpg: 'image/jpeg',
      jpeg: 'image/jpeg',
      png: 'image/png',
    };
    return map[ext] || 'application/octet-stream';
  }

  async uploadImage(file): Promise<string> {
    const filename = `${Date.now()}_${file.originalname}`;
    await this.client.put(`${storagePath}${filename}`, file.buffer, {
      headers: { 'Content-Type': file.mimetype },
    });
    return filename;
  }
}
